home *** CD-ROM | disk | FTP | other *** search
/ Windows Expert / Windows Expert.iso / windownt / tusrc.zip / SRC / TR.C < prev    next >
C/C++ Source or Header  |  1993-10-02  |  52KB  |  1,832 lines

  1. /* tr -- a filter to translate characters
  2.    Copyright (C) 1991 Free Software Foundation, Inc.
  3.  
  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 2, or (at your option)
  7.    any later version.
  8.  
  9.    This program is distributed in the hope that it will be useful,
  10.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.    GNU General Public License for more details.
  13.  
  14.    You should have received a copy of the GNU General Public License
  15.    along with this program; if not, write to the Free Software
  16.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
  17.  
  18. /* Written by Jim Meyering, meyering@cs.utexas.edu. */
  19.  
  20. /* Get isblank from GNU libc.  */
  21. #define _GNU_SOURCE
  22.  
  23. #include <stdio.h>
  24. #include <assert.h>
  25. #include <errno.h>
  26. #include <sys/types.h>
  27. #include <io.h>
  28. #include "../lib/getopt.h"
  29. #include "system.h"
  30. #include "version.h"
  31.  
  32. #ifndef LONG_MAX
  33. #define LONG_MAX 0x7FFFFFFF
  34. #endif
  35.  
  36. #ifndef UCHAR_MAX
  37. #define UCHAR_MAX 0xFF
  38. #endif
  39.  
  40. #define N_CHARS (UCHAR_MAX + 1)
  41.  
  42. /* A pointer to a function that returns an int. */
  43. typedef int (*PFI) ();
  44.  
  45. /* Convert from character C to its index in the collating
  46.    sequence array.  Just cast to an unsigned int to avoid
  47.    problems with sign-extension. */
  48. #define ORD(c) (unsigned int)(c)
  49.  
  50. /* The inverse of ORD. */
  51. #define CHR(i) (unsigned char)(i)
  52.  
  53. /* The value for Spec_list->state that indicates to
  54.    get_next that it should initialize the tail pointer.
  55.    Its value doesn't matter as long as it can't be
  56.    confused with a valid character code. */
  57. #define BEGIN_STATE (2 * N_CHARS)
  58.  
  59. /* The value for Spec_list->state that indicates to
  60.    get_next that the element pointed to by Spec_list->tail is
  61.    being considered for the first time on this pass through the
  62.    list -- it indicates that get_next should make any necessary
  63.    initializations. */
  64. #define NEW_ELEMENT (BEGIN_STATE + 1)
  65.  
  66. /* A value distinct from any character that may have been stored in a
  67.    buffer as the result of a block-read in the function squeeze_filter. */
  68. #define NOT_A_CHAR (unsigned int)(-1)
  69.  
  70. /* The following (but not CC_NO_CLASS) are indices into the array of
  71.    valid character class strings. */
  72. enum Char_class
  73.   {
  74.     CC_ALNUM = 0, CC_ALPHA = 1, CC_BLANK = 2, CC_CNTRL = 3,
  75.     CC_DIGIT = 4, CC_GRAPH = 5, CC_LOWER = 6, CC_PRINT = 7,
  76.     CC_PUNCT = 8, CC_SPACE = 9, CC_UPPER = 10, CC_XDIGIT = 11,
  77.     CC_NO_CLASS = 9999
  78.   };
  79.  
  80. /* Character class to which a character (returned by get_next) belonged;
  81.    but it is set only if the construct from which the character was obtained
  82.    was one of the character classes [:upper:] or [:lower:].  The value
  83.    is used only when translating and then, only to make sure that upper
  84.    and lower class constructs have the same relative positions in string1
  85.    and string2. */
  86. enum Upper_Lower_class
  87.   {
  88.     UL_LOWER = 0,
  89.     UL_UPPER = 1,
  90.     UL_NONE = 2
  91.   };
  92.  
  93. /* A shortcut to ensure that when constructing the translation array,
  94.    one of the values returned by paired calls to get_next (from s1 and s2)
  95.    is from [:upper:] and the other is from [:lower:], or neither is from
  96.    upper or lower.  In fact, no other character classes are allowed when
  97.    translating, but that condition is tested elsewhere.  This array is
  98.    indexed by values of type enum Upper_Lower_class. */
  99. static int const class_ok[3][3] =
  100. {
  101.   {0, 1, 0},
  102.   {1, 0, 0},
  103.   {0, 0, 1}
  104. };
  105.  
  106. /* The type of a List_element.  See build_spec_list for more details. */
  107. enum Range_element_type
  108.   {
  109.     RE_NO_TYPE = 0,
  110.     RE_NORMAL_CHAR,
  111.     RE_RANGE,
  112.     RE_CHAR_CLASS,
  113.     RE_EQUIV_CLASS,
  114.     RE_REPEATED_CHAR
  115.   };
  116.  
  117. /* One construct in one of tr's argument strings.
  118.    For example, consider the POSIX version of the classic tr command:
  119.        tr -cs 'a-zA-Z_' '[\n*]'
  120.    String1 has 3 constructs, two of which are ranges (a-z and A-Z),
  121.    and a single normal character, `_'.  String2 has one construct. */
  122. struct List_element
  123.   {
  124.     enum Range_element_type type;
  125.     struct List_element *next;
  126.     union
  127.       {
  128.     int normal_char;
  129.     struct            /* unnamed */
  130.       {
  131.         unsigned int first_char;
  132.         unsigned int last_char;
  133.       }
  134.     range;
  135.     enum Char_class char_class;
  136.     int equiv_code;
  137.     struct            /* unnamed */
  138.       {
  139.         unsigned int the_repeated_char;
  140.         long repeat_count;
  141.       }
  142.     repeated_char;
  143.       }
  144.     u;
  145.   };
  146.  
  147. /* Each of tr's argument strings is parsed into a form that is easier
  148.    to work with: a linked list of constructs (struct List_element).
  149.    Each Spec_list structure also encapsulates various attributes of
  150.    the corresponding argument string.  The attributes are used mainly
  151.    to verify that the strings are legal in the context of any options
  152.    specified (like -s, -d, or -c).  The main exception is the member
  153.    `tail', which is first used to construct the list.  After construction,
  154.    it is used by get_next to save its state when traversing the list.
  155.    The member `state' serves a similar function. */
  156. struct Spec_list
  157.   {
  158.     /* Points to the head of the list of range elements.
  159.        The first struct is a dummy; its members are never used. */
  160.     struct List_element *head;
  161.  
  162.     /* When appending, points to the last element.  When traversing via
  163.        get_next(), points to the element to process next.  Setting
  164.        Spec_list.state to the value BEGIN_STATE before calling get_next
  165.        signals get_next to initialize tail to point to head->next. */
  166.     struct List_element *tail;
  167.  
  168.     /* Used to save state between calls to get_next(). */
  169.     unsigned int state;
  170.  
  171.     /* Length, in the sense that length('a-z[:digit:]123abc')
  172.        is 42 ( = 26 + 10 + 6). */
  173.     int length;
  174.  
  175.     /* The number of [c*] and [c*0] constructs that appear in this spec. */
  176.     int n_indefinite_repeats;
  177.  
  178.     /* Non-zero if this spec contains at least one equivalence
  179.        class construct e.g. [=c=]. */
  180.     int has_equiv_class;
  181.  
  182.     /* Non-zero if this spec contains at least one of [:upper:] or
  183.        [:lower:] class constructs. */
  184.     int has_upper_or_lower;
  185.  
  186.     /* Non-zero if this spec contains at least one of the character class
  187.        constructs (all but upper and lower) that aren't allowed in s2. */
  188.     int has_restricted_char_class;
  189.   };
  190.  
  191. char *xmalloc ();
  192. char *stpcpy ();
  193. void error ();
  194.  
  195. /* The name by which this program was run. */
  196. char *program_name;
  197.  
  198. /* When non-zero, each sequence in the input of a repeated character
  199.    (call it c) is replaced (in the output) by a single occurrence of c
  200.    for every c in the squeeze set. */
  201. static int squeeze_repeats = 0;
  202.  
  203. /* When non-zero, removes characters in the delete set from input. */
  204. static int delete = 0;
  205.  
  206. /* Use the complement of set1 in place of set1. */
  207. static int complement = 0;
  208.  
  209. /* When non-zero, this flag causes GNU tr to provide strict
  210.    compliance with POSIX draft 1003.2.11.2.  The POSIX spec
  211.    says that when -d is used without -s, string2 (if present)
  212.    must be ignored.  Silently ignoring arguments is a bad idea.
  213.    The default GNU behavior is to give a usage message and exit.
  214.    Additionally, when this flag is non-zero, tr prints warnings
  215.    on stderr if it is being used in a manner that is not portable.
  216.    Applicable warnings are given by default, but are suppressed
  217.    if the environment variable `POSIXLY_CORRECT' is set, since
  218.    being POSIX conformant means we can't issue such messages.
  219.    Warnings on the following topics are suppressed when this
  220.    variable is non-zero:
  221.    1. Ambiguous octal escapes. */
  222. static int posix_pedantic;
  223.  
  224. /* When tr is performing translation and string1 is longer than string2,
  225.    POSIX says that the result is undefined.  That gives the implementor
  226.    of a POSIX conforming version of tr two reasonable choices for the
  227.    semantics of this case.
  228.  
  229.    * The BSD tr pads string2 to the length of string1 by
  230.    repeating the last character in string2.
  231.  
  232.    * System V tr ignores characters in string1 that have no
  233.    corresponding character in string2.  That is, string1 is effectively
  234.    truncated to the length of string2.
  235.  
  236.    When non-zero, this flag causes GNU tr to imitate the behavior
  237.    of System V tr when translating with string1 longer than string2.
  238.    The default is to emulate BSD tr.  This flag is ignored in modes where
  239.    no translation is performed.  Emulating the System V tr
  240.    in this exceptional case causes the relatively common BSD idiom:
  241.  
  242.        tr -cs A-Za-z0-9 '\012'
  243.  
  244.    to break (it would convert only zero bytes, rather than all
  245.    non-alphanumerics, to newlines).
  246.  
  247.    WARNING: This switch does not provide general BSD or System V
  248.    compatibility.  For example, it doesn't disable the interpretation
  249.    of the POSIX constructs [:alpha:], [=c=], and [c*10], so if by
  250.    some unfortunate coincidence you use such constructs in scripts
  251.    expecting to use some other version of tr, the scripts will break. */
  252. static int truncate_set1 = 0;
  253.  
  254. /* An alias for (!delete && non_option_args == 2).
  255.    It is set in main and used there and in validate(). */
  256. static int translating;
  257.  
  258. #ifndef BUFSIZ
  259. #define BUFSIZ 8192
  260. #endif
  261.  
  262. #define IO_BUF_SIZE BUFSIZ
  263. static unsigned char io_buf[IO_BUF_SIZE];
  264.  
  265. static char const *const char_class_name[] =
  266. {
  267.   "alnum", "alpha", "blank", "cntrl", "digit", "graph",
  268.   "lower", "print", "punct", "space", "upper", "xdigit"
  269. };
  270. #define N_CHAR_CLASSES (sizeof(char_class_name) / sizeof(char_class_name[0]))
  271.  
  272. typedef char SET_TYPE;
  273.  
  274. /* Array of boolean values.  A character `c' is a member of the
  275.    squeeze set if and only if in_squeeze_set[c] is true.  The squeeze
  276.    set is defined by the last (possibly, the only) string argument
  277.    on the command line when the squeeze option is given.  */
  278. static SET_TYPE in_squeeze_set[N_CHARS];
  279.  
  280. /* Array of boolean values.  A character `c' is a member of the
  281.    delete set if and only if in_delete_set[c] is true.  The delete
  282.    set is defined by the first (or only) string argument on the
  283.    command line when the delete option is given.  */
  284. static SET_TYPE in_delete_set[N_CHARS];
  285.  
  286. /* Array of character values defining the translation (if any) that
  287.    tr is to perform.  Translation is performed only when there are
  288.    two specification strings and the delete switch is not given. */
  289. static char xlate[N_CHARS];
  290.  
  291. /* If non-zero, display usage information and exit.  */
  292. static int flag_help;
  293.  
  294. /* If non-zero, print the version on standard error.  */
  295. static int flag_version;
  296.  
  297. static struct option const long_options[] =
  298. {
  299.   {"complement", no_argument, NULL, 'c'},
  300.   {"delete", no_argument, NULL, 'd'},
  301.   {"squeeze-repeats", no_argument, NULL, 's'},
  302.   {"truncate-set1", no_argument, NULL, 't'},
  303.   {"help", no_argument, &flag_help, 1},
  304.   {"version", no_argument, &flag_version, 1},
  305.   {NULL, 0, NULL, 0}
  306. };
  307.  
  308. static void
  309. usage ()
  310. {
  311.   fprintf (stderr, "\
  312. Usage: %s [-cdst] [--complement] [--delete] [--squeeze-repeats]\n\
  313.        [--truncate-set1] [--help] [--version] string1 [string2]\n",
  314.        program_name);
  315.   exit (2);
  316. }
  317.  
  318. /* Return non-zero if the character C is a member of the
  319.    equivalence class containing the character EQUIV_CLASS. */
  320.  
  321. static int
  322. is_equiv_class_member (equiv_class, c)
  323.      unsigned int equiv_class;
  324.      unsigned int c;
  325. {
  326.   return (equiv_class == c);
  327. }
  328.  
  329. /* Return non-zero if the character C is a member of the
  330.    character class CHAR_CLASS. */
  331.  
  332. static int
  333. is_char_class_member (char_class, c)
  334.      enum Char_class char_class;
  335.      unsigned int c;
  336. {
  337.   switch (char_class)
  338.     {
  339.     case CC_ALNUM:
  340.       return ISALNUM (c);
  341.       break;
  342.     case CC_ALPHA:
  343.       return ISALPHA (c);
  344.       break;
  345.     case CC_BLANK:
  346.       return ISBLANK (c);
  347.       break;
  348.     case CC_CNTRL:
  349.       return ISCNTRL (c);
  350.       break;
  351.     case CC_DIGIT:
  352.       return ISDIGIT (c);
  353.       break;
  354.     case CC_GRAPH:
  355.       return ISGRAPH (c);
  356.       break;
  357.     case CC_LOWER:
  358.       return ISLOWER (c);
  359.       break;
  360.     case CC_PRINT:
  361.       return ISPRINT (c);
  362.       break;
  363.     case CC_PUNCT:
  364.       return ISPUNCT (c);
  365.       break;
  366.     case CC_SPACE:
  367.       return ISSPACE (c);
  368.       break;
  369.     case CC_UPPER:
  370.       return ISUPPER (c);
  371.       break;
  372.     case CC_XDIGIT:
  373.       return ISXDIGIT (c);
  374.       break;
  375.     default:
  376.       abort ();
  377.       break;
  378.     }
  379. }
  380.  
  381. /* Perform the first pass over each range-spec argument S,
  382.    converting all \c and \ddd escapes to their one-byte representations.
  383.    The conversion is done in-place, so S must point to writable
  384.    storage.  If an illegal quote sequence is found, an error message is
  385.    printed and the function returns non-zero.  Otherwise the length of
  386.    the resulting string is returned through LEN and the function returns 0.
  387.    The resulting array of characters may contain zero-bytes; however,
  388.    on input, S is assumed to be null-terminated, and hence
  389.    cannot contain actual (non-escaped) zero bytes. */
  390.  
  391. static int
  392. unquote (s, len)
  393.      unsigned char *s;
  394.      int *len;
  395. {
  396.   int i, j;
  397.  
  398.   j = 0;
  399.   for (i = 0; s[i]; i++)
  400.     {
  401.       switch (s[i])
  402.     {
  403.       int c;
  404.     case '\\':
  405.       switch (s[i + 1])
  406.         {
  407.           int oct_digit;
  408.         case '\\':
  409.           c = '\\';
  410.           break;
  411.         case 'a':
  412.           c = '\007';
  413.           break;
  414.         case 'b':
  415.           c = '\b';
  416.           break;
  417.         case 'f':
  418.           c = '\f';
  419.           break;
  420.         case 'n':
  421.           c = '\n';
  422.           break;
  423.         case 'r':
  424.           c = '\r';
  425.           break;
  426.         case 't':
  427.           c = '\t';
  428.           break;
  429.         case 'v':
  430.           c = '\v';
  431.           break;
  432.         case '0':
  433.         case '1':
  434.         case '2':
  435.         case '3':
  436.         case '4':
  437.         case '5':
  438.         case '6':
  439.         case '7':
  440.           c = s[i + 1] - '0';
  441.           oct_digit = s[i + 2] - '0';
  442.           if (0 <= oct_digit && oct_digit <= 7)
  443.         {
  444.           c = 8 * c + oct_digit;
  445.           ++i;
  446.           oct_digit = s[i + 2] - '0';
  447.           if (0 <= oct_digit && oct_digit <= 7)
  448.             {
  449.               if (8 * c + oct_digit < N_CHARS)
  450.             {
  451.               c = 8 * c + oct_digit;
  452.               ++i;
  453.             }
  454.               else if (!posix_pedantic)
  455.             {
  456.               /* Any octal number larger than 0377 won't
  457.                  fit in 8 bits.  So we stop when adding the
  458.                  next digit would put us over the limit and
  459.                  give a warning about the ambiguity.  POSIX
  460.                  isn't clear on this, but one person has said
  461.                  that in his interpretation, POSIX says tr
  462.                  can't even give a warning. */
  463.               error (0, 0, "warning: the ambiguous octal escape \
  464. \\%c%c%c is being\n\tinterpreted as the 2-byte sequence \\0%c%c, `%c'",
  465.                  s[i], s[i + 1], s[i + 2],
  466.                  s[i], s[i + 1], s[i + 2]);
  467.             }
  468.             }
  469.         }
  470.           break;
  471.         case '\0':
  472.           error (0, 0, "invalid backslash escape at end of string");
  473.           return 1;
  474.           break;
  475.         default:
  476.           error (0, 0, "invalid backslash escape `\\%c'", s[i + 1]);
  477.           return 1;
  478.           break;
  479.         }
  480.       ++i;
  481.       s[j++] = c;
  482.       break;
  483.     default:
  484.       s[j++] = s[i];
  485.       break;
  486.     }
  487.     }
  488.   *len = j;
  489.   return 0;
  490. }
  491.  
  492. /* If CLASS_STR is a valid character class string, return its index
  493.    in the global char_class_name array.  Otherwise, return CC_NO_CLASS. */
  494.  
  495. static enum Char_class
  496. look_up_char_class (class_str)
  497.      unsigned char *class_str;
  498. {
  499.   unsigned int i;
  500.  
  501.   for (i = 0; i < N_CHAR_CLASSES; i++)
  502.     if (strcmp ((const char *) class_str, char_class_name[i]) == 0)
  503.       return (enum Char_class) i;
  504.   return CC_NO_CLASS;
  505. }
  506.  
  507. /* Return a newly allocated string with a printable version of C.
  508.    This function is used solely for formatting error messages. */
  509.  
  510. static char *
  511. make_printable_char (c)
  512.      unsigned int c;
  513. {
  514.   char *buf = xmalloc (5);
  515.  
  516.   assert (c < N_CHARS);
  517.   if (ISPRINT (c))
  518.     {
  519.       buf[0] = c;
  520.       buf[1] = '\0';
  521.     }
  522.   else
  523.     {
  524.       sprintf (buf, "\\%03o", c);
  525.     }
  526.   return buf;
  527. }
  528.  
  529. /* Return a newly allocated copy of S which is suitable for printing.
  530.    LEN is the number of characters in S.  Most non-printing
  531.    (isprint) characters are represented by a backslash followed by
  532.    3 octal digits.  However, the characters represented by \c escapes
  533.    where c is one of [abfnrtv] are represented by their 2-character \c
  534.    sequences.  This function is used solely for printing error messages. */
  535.  
  536. static char *
  537. make_printable_str (s, len)
  538.      unsigned char *s;
  539.      int len;
  540. {
  541.   /* Worst case is that every character expands to a backslash
  542.      followed by a 3-character octal escape sequence. */
  543.   char *printable_buf = xmalloc (4 * len + 1);
  544.   char *p = printable_buf;
  545.   int i;
  546.  
  547.   for (i = 0; i < len; i++)
  548.     {
  549.       char buf[5];
  550.       char *tmp = NULL;
  551.  
  552.       switch (s[i])
  553.     {
  554.     case '\\':
  555.       tmp = "\\";
  556.       break;
  557.     case '\007':
  558.       tmp = "\\a";
  559.       break;
  560.     case '\b':
  561.       tmp = "\\b";
  562.       break;
  563.     case '\f':
  564.       tmp = "\\f";
  565.       break;
  566.     case '\n':
  567.       tmp = "\\n";
  568.       break;
  569.     case '\r':
  570.       tmp = "\\r";
  571.       break;
  572.     case '\t':
  573.       tmp = "\\t";
  574.       break;
  575.     case '\v':
  576.       tmp = "\\v";
  577.       break;
  578.     default:
  579.       if (ISPRINT (s[i]))
  580.         {
  581.           buf[0] = s[i];
  582.           buf[1] = '\0';
  583.         }
  584.       else
  585.         sprintf (buf, "\\%03o", s[i]);
  586.       tmp = buf;
  587.       break;
  588.     }
  589.       p = stpcpy (p, tmp);
  590.     }
  591.   return printable_buf;
  592. }
  593.  
  594. /* Append a newly allocated structure representing a
  595.    character C to the specification list LIST. */
  596.  
  597. static void
  598. append_normal_char (list, c)
  599.      struct Spec_list *list;
  600.      unsigned int c;
  601. {
  602.   struct List_element *new;
  603.  
  604.   new = (struct List_element *) xmalloc (sizeof (struct List_element));
  605.   new->next = NULL;
  606.   new->type = RE_NORMAL_CHAR;
  607.   new->u.normal_char = c;
  608.   assert (list->tail);
  609.   list->tail->next = new;
  610.   list->tail = new;
  611. }
  612.  
  613. /* Append a newly allocated structure representing the range
  614.    of characters from FIRST to LAST to the specification list LIST.
  615.    Return non-zero if LAST precedes FIRST in the collating sequence,
  616.    zero otherwise.  This means that '[c-c]' is acceptable.  */
  617.  
  618. static int
  619. append_range (list, first, last)
  620.      struct Spec_list *list;
  621.      unsigned int first;
  622.      unsigned int last;
  623. {
  624.   struct List_element *new;
  625.  
  626.   if (ORD (first) > ORD (last))
  627.     {
  628.       char *tmp1 = make_printable_char (first);
  629.       char *tmp2 = make_printable_char (last);
  630.  
  631.       error (0, 0,
  632.        "range-endpoints of `%s-%s' are in reverse collating sequence order",
  633.          tmp1, tmp2);
  634.       free (tmp1);
  635.       free (tmp2);
  636.       return 1;
  637.     }
  638.   new = (struct List_element *) xmalloc (sizeof (struct List_element));
  639.   new->next = NULL;
  640.   new->type = RE_RANGE;
  641.   new->u.range.first_char = first;
  642.   new->u.range.last_char = last;
  643.   assert (list->tail);
  644.   list->tail->next = new;
  645.   list->tail = new;
  646.   return 0;
  647. }
  648.  
  649. /* If CHAR_CLASS_STR is a valid character class string, append a
  650.    newly allocated structure representing that character class to the end
  651.    of the specification list LIST and return 0.  If CHAR_CLASS_STR is not
  652.    a valid string, give an error message and return non-zero. */
  653.  
  654. static int
  655. append_char_class (list, char_class_str, len)
  656.      struct Spec_list *list;
  657.      unsigned char *char_class_str;
  658.      int len;
  659. {
  660.   enum Char_class char_class;
  661.   struct List_element *new;
  662.  
  663.   char_class = look_up_char_class (char_class_str);
  664.   if (char_class == CC_NO_CLASS)
  665.     {
  666.       char *tmp = make_printable_str (char_class_str, len);
  667.  
  668.       error (0, 0, "invalid character class `%s'", tmp);
  669.       free (tmp);
  670.       return 1;
  671.     }
  672.   new = (struct List_element *) xmalloc (sizeof (struct List_element));
  673.   new->next = NULL;
  674.   new->type = RE_CHAR_CLASS;
  675.   new->u.char_class = char_class;
  676.   assert (list->tail);
  677.   list->tail->next = new;
  678.   list->tail = new;
  679.   return 0;
  680. }
  681.  
  682. /* Append a newly allocated structure representing a [c*n]
  683.    repeated character construct, to the specification list LIST.
  684.    THE_CHAR is the single character to be repeated, and REPEAT_COUNT
  685.    is non-negative repeat count. */
  686.  
  687. static void
  688. append_repeated_char (list, the_char, repeat_count)
  689.      struct Spec_list *list;
  690.      unsigned int the_char;
  691.      long int repeat_count;
  692. {
  693.   struct List_element *new;
  694.  
  695.   new = (struct List_element *) xmalloc (sizeof (struct List_element));
  696.   new->next = NULL;
  697.   new->type = RE_REPEATED_CHAR;
  698.   new->u.repeated_char.the_repeated_char = the_char;
  699.   new->u.repeated_char.repeat_count = repeat_count;
  700.   assert (list->tail);
  701.   list->tail->next = new;
  702.   list->tail = new;
  703. }
  704.  
  705. /* Given a string, EQUIV_CLASS_STR, from a [=str=] context and
  706.    the length of that string, LEN, if LEN is exactly one, append
  707.    a newly allocated structure representing the specified
  708.    equivalence class to the specification list, LIST and return zero.
  709.    If LEN is not 1, issue an error message and return non-zero. */
  710.  
  711. static int
  712. append_equiv_class (list, equiv_class_str, len)
  713.      struct Spec_list *list;
  714.      unsigned char *equiv_class_str;
  715.      int len;
  716. {
  717.   struct List_element *new;
  718.  
  719.   if (len != 1)
  720.     {
  721.       char *tmp = make_printable_str (equiv_class_str, len);
  722.  
  723.       error (0, 0, "%s: equivalence class operand must be a single character",
  724.          tmp);
  725.       free (tmp);
  726.       return 1;
  727.     }
  728.   new = (struct List_element *) xmalloc (sizeof (struct List_element));
  729.   new->next = NULL;
  730.   new->type = RE_EQUIV_CLASS;
  731.   new->u.equiv_code = *equiv_class_str;
  732.   assert (list->tail);
  733.   list->tail->next = new;
  734.   list->tail = new;
  735.   return 0;
  736. }
  737.  
  738. /* Return a newly allocated copy of P[FIRST_IDX..LAST_IDX]. */
  739.  
  740. static unsigned char *
  741. substr (p, first_idx, last_idx)
  742.      unsigned char *p;
  743.      int first_idx;
  744.      int last_idx;
  745. {
  746.   int len = last_idx - first_idx + 1;
  747.   unsigned char *tmp = (unsigned char *) xmalloc (len);
  748.  
  749.   assert (first_idx <= last_idx);
  750.   /* We must use bcopy or memcopy rather than strncpy
  751.      because `p' may contain zero-bytes. */
  752.   bcopy (p + first_idx, tmp, len);
  753.   tmp[len] = '\0';
  754.   return tmp;
  755. }
  756.  
  757. /* Search forward starting at START_IDX for the 2-char sequence
  758.    (PRE_BRACKET_CHAR,']') in the string P of length P_LEN.  If such
  759.    a sequence is found, return the index of the first character,
  760.    otherwise return -1.  P may contain zero bytes. */
  761.  
  762. static int
  763. find_closing_delim (p, start_idx, p_len, pre_bracket_char)
  764.      unsigned char *p;
  765.      int start_idx;
  766.      int p_len;
  767.      unsigned int pre_bracket_char;
  768. {
  769.   int i;
  770.  
  771.   for (i = start_idx; i < p_len - 1; i++)
  772.     if (p[i] == pre_bracket_char && p[i + 1] == ']')
  773.       return i;
  774.   return -1;
  775. }
  776.  
  777. /* Convert a string S with explicit length LEN, possibly
  778.    containing embedded zero bytes, to a long integer value.
  779.    If the string represents a negative value, a value larger
  780.    than LONG_MAX, or if all LEN characters do not represent a
  781.    valid integer, return non-zero and do not modify *VAL.
  782.    Otherwise, return zero and set *VAL to the converted value. */
  783.  
  784. static int
  785. non_neg_strtol (s, len, val)
  786.      unsigned char *s;
  787.      int len;
  788.      long int *val;
  789. {
  790.   int i;
  791.   long sum = 0;
  792.   unsigned int base;
  793.  
  794.   if (len <= 0)
  795.     return 1;
  796.   if (s[0] == '0')
  797.     base = 8;
  798.   else if (ISDIGIT (s[0]))
  799.     base = 10;
  800.   else
  801.     return 1;
  802.  
  803.   for (i = 0; i < len; i++)
  804.     {
  805.       int c = s[i] - '0';
  806.  
  807.       if ((unsigned) c >= base || c < 0)
  808.     return 1;
  809.       if (i > (int) 8 && (unsigned) sum > (LONG_MAX - c) / base)
  810.     return 1;
  811.       sum = sum * base + c;
  812.     }
  813.   *val = sum;
  814.   return 0;
  815. }
  816.  
  817. /* Parse the bracketed repeat-char syntax.  If the P_LEN characters
  818.    beginning with P[ START_IDX ] comprise a valid [c*n] construct,
  819.    return the character and the repeat count through the arg pointers,
  820.    CHAR_TO_REPEAT and N, and then return the index of the closing
  821.    bracket as the function value.  If the second character following
  822.    the opening bracket is not `*' or if no closing bracket can be
  823.    found, return -1.  If a closing bracket is found and the
  824.    second char is `*', but the string between the `*' and `]' isn't
  825.    empty, an octal number, or a decimal number, print an error message
  826.    and return -2. */
  827.  
  828. static int
  829. find_bracketed_repeat (p, start_idx, p_len, char_to_repeat, n)
  830.      unsigned char *p;
  831.      int start_idx;
  832.      int p_len;
  833.      unsigned int *char_to_repeat;
  834.      long int *n;
  835. {
  836.   int i;
  837.  
  838.   assert (start_idx + 1 < p_len);
  839.   if (p[start_idx + 1] != '*')
  840.     return -1;
  841.  
  842.   for (i = start_idx + 2; i < p_len; i++)
  843.     {
  844.       if (p[i] == ']')
  845.     {
  846.       unsigned char *digit_str;
  847.       int digit_str_len = i - start_idx - 2;
  848.  
  849.       *char_to_repeat = p[start_idx];
  850.       if (digit_str_len == 0)
  851.         {
  852.           /* We've matched [c*] -- no explicit repeat count. */
  853.           *n = 0;
  854.           return i;
  855.         }
  856.  
  857.       /* Here, we have found [c*s] where s should be a string
  858.          of octal or decimal digits. */
  859.       digit_str = &p[start_idx + 2];
  860.       if (non_neg_strtol (digit_str, digit_str_len, n))
  861.         {
  862.           char *tmp = make_printable_str (digit_str, digit_str_len);
  863.           error (0, 0, "invalid repeat count `%s' in [c*n] construct", tmp);
  864.           free (tmp);
  865.           return -2;
  866.         }
  867.       return i;
  868.     }
  869.     }
  870.   return -1;            /* No bracket found. */
  871. }
  872.  
  873. /* Convert string UNESACPED_STRING (which has been preprocessed to
  874.    convert backslash-escape sequences) of length LEN characters into
  875.    a linked list of the following 5 types of constructs:
  876.       - [:str:] Character class where `str' is one of the 12 valid strings.
  877.       - [=c=] Equivalence class where `c' is any single character.
  878.       - [c*n] Repeat the single character `c' `n' times. n may be omitted.
  879.       However, if `n' is present, it must be a non-negative octal or
  880.       decimal integer.
  881.       - r-s Range of characters from `r' to `s'.  The second endpoint must
  882.       not precede the first in the current collating sequence.
  883.       - c Any other character is interpreted as itself. */
  884.  
  885. static int
  886. build_spec_list (unescaped_string, len, result)
  887.      unsigned char *unescaped_string;
  888.      int len;
  889.      struct Spec_list *result;
  890. {
  891.   unsigned char *p;
  892.   int i;
  893.  
  894.   p = unescaped_string;
  895.  
  896.   /* The main for-loop below recognizes the 4 multi-character constructs.
  897.      A character that matches (in its context) none of the multi-character
  898.      constructs is classified as `normal'.  Since all multi-character
  899.      constructs have at least 3 characters, any strings of length 2 or
  900.      less are composed solely of normal characters.  Hence, the index of
  901.      the outer for-loop runs only as far as LEN-2. */
  902.  
  903.   for (i = 0; i < len - 2;)
  904.     {
  905.       switch (p[i])
  906.     {
  907.       int fall_through;
  908.     case '[':
  909.       fall_through = 0;
  910.       switch (p[i + 1])
  911.         {
  912.           int closing_delim_idx;
  913.           int closing_bracket_idx;
  914.           unsigned int char_to_repeat;
  915.           long repeat_count;
  916.         case ':':
  917.         case '=':
  918.           closing_delim_idx = find_closing_delim (p, i + 2, len, p[i + 1]);
  919.           if (closing_delim_idx >= 0)
  920.         {
  921.           int parse_failed;
  922.           unsigned char *opnd_str = substr (p, i + 2, closing_delim_idx - 1);
  923.           if (p[i + 1] == ':')
  924.             parse_failed = append_char_class (result, opnd_str,
  925.                      (closing_delim_idx - 1) - (i + 2) + 1);
  926.           else
  927.             parse_failed = append_equiv_class (result, opnd_str,
  928.                      (closing_delim_idx - 1) - (i + 2) + 1);
  929.           free (opnd_str);
  930.  
  931.           /* Return non-zero if append_*_class reports a problem. */
  932.           if (parse_failed)
  933.             return 1;
  934.           else
  935.             i = closing_delim_idx + 2;
  936.           break;
  937.         }
  938.           /* Else fall through.  This could be [:*] or [=*]. */
  939.         default:
  940.           /* Determine whether this is a bracketed repeat range
  941.          matching the RE \[.\*(dec_or_oct_number)?\]. */
  942.           closing_bracket_idx = find_bracketed_repeat (p, i + 1,
  943.                        len, &char_to_repeat, &repeat_count);
  944.           if (closing_bracket_idx >= 0)
  945.         {
  946.           append_repeated_char (result, char_to_repeat, repeat_count);
  947.           i = closing_bracket_idx + 1;
  948.           break;
  949.         }
  950.           else if (closing_bracket_idx == -1)
  951.         {
  952.           fall_through = 1;
  953.         }
  954.           else
  955.         /* Found a string that looked like [c*n] but the
  956.            numeric part was invalid. */
  957.         return 1;
  958.           break;
  959.         }
  960.       if (!fall_through)
  961.         break;
  962.  
  963.       /* Here if we've tried to match [c*n], [:str:], and [=c=]
  964.          and none of them fit.  So we still have to consider the
  965.          range `[-c' (from `[' to `c'). */
  966.     default:
  967.       /* Look ahead one char for ranges like a-z. */
  968.       if (p[i + 1] == '-')
  969.         {
  970.           if (append_range (result, p[i], p[i + 2]))
  971.         return 1;
  972.           i += 3;
  973.         }
  974.       else
  975.         {
  976.           append_normal_char (result, p[i]);
  977.           ++i;
  978.         }
  979.       break;
  980.     }
  981.     }
  982.  
  983.   /* Now handle the (2 or fewer) remaining characters p[i]..p[len - 1]. */
  984.   for (; i < len; i++)
  985.     append_normal_char (result, p[i]);
  986.  
  987.   return 0;
  988. }
  989.  
  990. /* Given a Spec_list S (with its saved state implicit in the values
  991.    of its members `tail' and `state'), return the next single character
  992.    in the expansion of S's constructs.  If the last character of S was
  993.    returned on the previous call or if S was empty, this function
  994.    returns -1.  For example, successive calls to get_next where S
  995.    represents the spec-string 'a-d[y*3]' will return the sequence
  996.    of values a, b, c, d, y, y, y, -1.  Finally, if the construct from
  997.    which the returned character comes is [:upper:] or [:lower:], the
  998.    parameter CLASS is given a value to indicate which it was.  Otherwise
  999.    CLASS is set to UL_NONE.  This value is used only when constructing
  1000.    the translation table to verify that any occurrences of upper and
  1001.    lower class constructs in the spec-strings appear in the same relative
  1002.    positions. */
  1003.  
  1004. static int
  1005. get_next (s, class)
  1006.      struct Spec_list *s;
  1007.      enum Upper_Lower_class *class;
  1008. {
  1009.   struct List_element *p;
  1010.   int return_val;
  1011.   int i;
  1012.  
  1013.   if (class)
  1014.     *class = UL_NONE;
  1015.  
  1016.   if (s->state == BEGIN_STATE)
  1017.     {
  1018.       s->tail = s->head->next;
  1019.       s->state = NEW_ELEMENT;
  1020.     }
  1021.  
  1022.   p = s->tail;
  1023.   if (p == NULL)
  1024.     return -1;
  1025.  
  1026.   switch (p->type)
  1027.     {
  1028.     case RE_NORMAL_CHAR:
  1029.       return_val = p->u.normal_char;
  1030.       s->state = NEW_ELEMENT;
  1031.       s->tail = p->next;
  1032.       break;
  1033.  
  1034.     case RE_RANGE:
  1035.       if (s->state == NEW_ELEMENT)
  1036.     s->state = ORD (p->u.range.first_char);
  1037.       else
  1038.     ++(s->state);
  1039.       return_val = CHR (s->state);
  1040.       if (s->state == ORD (p->u.range.last_char))
  1041.     {
  1042.       s->tail = p->next;
  1043.       s->state = NEW_ELEMENT;
  1044.     }
  1045.       break;
  1046.  
  1047.     case RE_CHAR_CLASS:
  1048.       if (s->state == NEW_ELEMENT)
  1049.     {
  1050.       for (i = 0; i < N_CHARS; i++)
  1051.         if (is_char_class_member (p->u.char_class, i))
  1052.           break;
  1053.       assert (i < N_CHARS);
  1054.       s->state = i;
  1055.     }
  1056.       assert (is_char_class_member (p->u.char_class, s->state));
  1057.       return_val = CHR (s->state);
  1058.       for (i = s->state + 1; i < N_CHARS; i++)
  1059.     if (is_char_class_member (p->u.char_class, i))
  1060.       break;
  1061.       if (i < N_CHARS)
  1062.     s->state = i;
  1063.       else
  1064.     {
  1065.       s->tail = p->next;
  1066.       s->state = NEW_ELEMENT;
  1067.     }
  1068.       if (class)
  1069.     {
  1070.       switch (p->u.char_class)
  1071.         {
  1072.         case CC_LOWER:
  1073.           *class = UL_LOWER;
  1074.           break;
  1075.         case CC_UPPER:
  1076.           *class = UL_UPPER;
  1077.           break;
  1078.         default:
  1079.           /* empty */
  1080.           break;
  1081.         }
  1082.     }
  1083.       break;
  1084.  
  1085.     case RE_EQUIV_CLASS:
  1086.       /* FIXME: this assumes that each character is alone in its own
  1087.      equivalence class (which appears to be correct for my
  1088.      LC_COLLATE.  But I don't know of any function that allows
  1089.      one to determine a character's equivalence class. */
  1090.  
  1091.       return_val = p->u.equiv_code;
  1092.       s->state = NEW_ELEMENT;
  1093.       s->tail = p->next;
  1094.       break;
  1095.  
  1096.     case RE_REPEATED_CHAR:
  1097.       /* Here, a repeat count of n == 0 means don't repeat at all. */
  1098.       assert (p->u.repeated_char.repeat_count >= 0);
  1099.       if (p->u.repeated_char.repeat_count == 0)
  1100.     {
  1101.       s->tail = p->next;
  1102.       s->state = NEW_ELEMENT;
  1103.       return_val = get_next (s, class);
  1104.     }
  1105.       else
  1106.     {
  1107.       if (s->state == NEW_ELEMENT)
  1108.         {
  1109.           s->state = 0;
  1110.         }
  1111.       ++(s->state);
  1112.       return_val = p->u.repeated_char.the_repeated_char;
  1113.       if (p->u.repeated_char.repeat_count > 0
  1114.           && s->state == (unsigned) p->u.repeated_char.repeat_count)
  1115.         {
  1116.           s->tail = p->next;
  1117.           s->state = NEW_ELEMENT;
  1118.         }
  1119.     }
  1120.       break;
  1121.  
  1122.     case RE_NO_TYPE:
  1123.       abort ();
  1124.       break;
  1125.     }
  1126.   return return_val;
  1127. }
  1128.  
  1129. /* This is a minor kludge.  This function is called from
  1130.    get_spec_stats to determine the cardinality of a set derived
  1131.    from a complemented string.  It's a kludge in that some of
  1132.    the same operations are (duplicated) performed in set_initialize. */
  1133.  
  1134. static int
  1135. card_of_complement (s)
  1136.      struct Spec_list *s;
  1137. {
  1138.   int c;
  1139.   int cardinality = N_CHARS;
  1140.   SET_TYPE in_set[N_CHARS];
  1141.  
  1142.   bzero (in_set, N_CHARS * sizeof (in_set[0]));
  1143.   s->state = BEGIN_STATE;
  1144.   while ((c = get_next (s, NULL)) != -1)
  1145.     if (!in_set[c]++)
  1146.       --cardinality;
  1147.   return cardinality;
  1148. }
  1149.  
  1150. /* Gather statistics about the spec-list S in preparation for the tests
  1151.    in validate that determine the legality of the specs.  This function
  1152.    is called at most twice; once for string1, and again for any string2.
  1153.    LEN_S1 < 0 indicates that this is the first call and that S represents
  1154.    string1.  When LEN_S1 >= 0, it is the length of the expansion of the
  1155.    constructs in string1, and we can use its value to resolve any
  1156.    indefinite repeat construct in S (which represents string2).  Hence,
  1157.    this function has the side-effect that it converts a valid [c*]
  1158.    construct in string2 to [c*n] where n is large enough (or 0) to give
  1159.    string2 the same length as string1.  For example, with the command
  1160.    tr a-z 'A[\n*]Z' on the second call to get_spec_stats, LEN_S1 would
  1161.    be 26 and S (representing string2) would be converted to 'A[\n*24]Z'. */
  1162.  
  1163. static void
  1164. get_spec_stats (s, len_s1)
  1165.      struct Spec_list *s;
  1166.      int len_s1;
  1167. {
  1168.   struct List_element *p;
  1169.   struct List_element *indefinite_repeat_element = NULL;
  1170.   int len = 0;
  1171.  
  1172.   s->n_indefinite_repeats = 0;
  1173.   s->has_equiv_class = 0;
  1174.   s->has_restricted_char_class = 0;
  1175.   s->has_upper_or_lower = 0;
  1176.   for (p = s->head->next; p; p = p->next)
  1177.     {
  1178.       switch (p->type)
  1179.     {
  1180.       int i;
  1181.     case RE_NORMAL_CHAR:
  1182.       ++len;
  1183.       break;
  1184.  
  1185.     case RE_RANGE:
  1186.       assert (p->u.range.last_char >= p->u.range.first_char);
  1187.       len += p->u.range.last_char - p->u.range.first_char + 1;
  1188.       break;
  1189.  
  1190.     case RE_CHAR_CLASS:
  1191.       for (i = 0; i < N_CHARS; i++)
  1192.         if (is_char_class_member (p->u.char_class, i))
  1193.           ++len;
  1194.       switch (p->u.char_class)
  1195.         {
  1196.         case CC_UPPER:
  1197.         case CC_LOWER:
  1198.           s->has_upper_or_lower = 1;
  1199.           break;
  1200.         default:
  1201.           s->has_restricted_char_class = 1;
  1202.           break;
  1203.         }
  1204.       break;
  1205.  
  1206.     case RE_EQUIV_CLASS:
  1207.       for (i = 0; i < N_CHARS; i++)
  1208.         if (is_equiv_class_member (p->u.equiv_code, i))
  1209.           ++len;
  1210.       s->has_equiv_class = 1;
  1211.       break;
  1212.  
  1213.     case RE_REPEATED_CHAR:
  1214.       if (p->u.repeated_char.repeat_count > 0)
  1215.         len += p->u.repeated_char.repeat_count;
  1216.       else if (p->u.repeated_char.repeat_count == 0)
  1217.         {
  1218.           indefinite_repeat_element = p;
  1219.           ++(s->n_indefinite_repeats);
  1220.         }
  1221.       break;
  1222.  
  1223.     case RE_NO_TYPE:
  1224.       assert (0);
  1225.       break;
  1226.     }
  1227.     }
  1228.  
  1229.   if (len_s1 >= len && s->n_indefinite_repeats == 1)
  1230.     {
  1231.       indefinite_repeat_element->u.repeated_char.repeat_count = len_s1 - len;
  1232.       len = len_s1;
  1233.     }
  1234.   if (complement && len_s1 < 0)
  1235.     s->length = card_of_complement (s);
  1236.   else
  1237.     s->length = len;
  1238.   return;
  1239. }
  1240.  
  1241. static void
  1242. spec_init (spec_list)
  1243.      struct Spec_list *spec_list;
  1244. {
  1245.   spec_list->head = spec_list->tail =
  1246.     (struct List_element *) xmalloc (sizeof (struct List_element));
  1247.   spec_list->head->next = NULL;
  1248. }
  1249.  
  1250. /* This function makes two passes over the argument string S.  The first
  1251.    one converts all \c and \ddd escapes to their one-byte representations.
  1252.    The second constructs a linked specification list, SPEC_LIST, of the
  1253.    characters and constructs that comprise the argument string.  If either
  1254.    of these passes detects an error, this function returns non-zero. */
  1255.  
  1256. static int
  1257. parse_str (s, spec_list)
  1258.      unsigned char *s;
  1259.      struct Spec_list *spec_list;
  1260. {
  1261.   int len;
  1262.  
  1263.   if (unquote (s, &len))
  1264.     return 1;
  1265.   if (build_spec_list (s, len, spec_list))
  1266.     return 1;
  1267.   return 0;
  1268. }
  1269.  
  1270. /* Given two specification lists, S1 and S2, and assuming that
  1271.    S1->length > S2->length, append a single [c*n] element to S2 where c
  1272.    is the last character in the expansion of S2 and n is the difference
  1273.    between the two lengths.
  1274.    Upon successful completion, S2->length is set to S1->length.  The only
  1275.    way this function can fail to make S2 as long as S1 is when S2 has
  1276.    zero-length, since in that case, there is no last character to repeat.
  1277.    So S2->length is required to be at least 1.
  1278.  
  1279.    Providing this functionality allows the user to do some pretty
  1280.    non-BSD (and non-portable) things:  For example, the command
  1281.        tr -cs '[:upper:]0-9' '[:lower:]'
  1282.    is almost guaranteed to give results that depend on your collating
  1283.    sequence.  */
  1284.  
  1285. static void
  1286. string2_extend (s1, s2)
  1287.      struct Spec_list *s1;
  1288.      struct Spec_list *s2;
  1289. {
  1290.   struct List_element *p;
  1291.   int char_to_repeat;
  1292.   int i;
  1293.  
  1294.   assert (translating);
  1295.   assert (s1->length > s2->length);
  1296.   assert (s2->length > 0);
  1297.  
  1298.   p = s2->tail;
  1299.   switch (p->type)
  1300.     {
  1301.     case RE_NORMAL_CHAR:
  1302.       char_to_repeat = p->u.normal_char;
  1303.       break;
  1304.     case RE_RANGE:
  1305.       char_to_repeat = p->u.range.last_char;
  1306.       break;
  1307.     case RE_CHAR_CLASS:
  1308.       for (i = N_CHARS; i >= 0; i--)
  1309.     if (is_char_class_member (p->u.char_class, i))
  1310.       break;
  1311.       assert (i >= 0);
  1312.       char_to_repeat = CHR (i);
  1313.       break;
  1314.  
  1315.     case RE_REPEATED_CHAR:
  1316.       char_to_repeat = p->u.repeated_char.the_repeated_char;
  1317.       break;
  1318.  
  1319.     case RE_EQUIV_CLASS:
  1320.       /* This shouldn't happen, because validate exits with an error
  1321.      if it finds an equiv class in string2 when translating. */
  1322.       abort ();
  1323.       break;
  1324.  
  1325.     case RE_NO_TYPE:
  1326.       abort ();
  1327.       break;
  1328.     }
  1329.   append_repeated_char (s2, char_to_repeat, s1->length - s2->length);
  1330.   s2->length = s1->length;
  1331.   return;
  1332. }
  1333.  
  1334. /* Die with an error message if S1 and S2 describe strings that
  1335.    are not valid with the given command line switches.
  1336.    A side effect of this function is that if a legal [c*] or
  1337.    [c*0] construct appears in string2, it is converted to [c*n]
  1338.    with a value for n that makes s2->length == s1->length.  By
  1339.    the same token, if the --truncate-set1 option is not
  1340.    given, S2 may be extended. */
  1341.  
  1342. static void
  1343. validate (s1, s2)
  1344.      struct Spec_list *s1;
  1345.      struct Spec_list *s2;
  1346. {
  1347.   get_spec_stats (s1, -1);
  1348.   if (s1->n_indefinite_repeats > 0)
  1349.     {
  1350.       error (1, 0, "the [c*] repeat construct may not appear in string1");
  1351.     }
  1352.  
  1353.   /* FIXME: it isn't clear from the POSIX spec that this is illegal,
  1354.      but in the spirit of the other restrictions put on translation
  1355.      with character classes, this seems a logical interpretation. */
  1356.   if (complement && s1->has_upper_or_lower)
  1357.     {
  1358.       error (1, 0,
  1359.          "character classes may not be used when translating and complementing");
  1360.     }
  1361.  
  1362.   if (s2)
  1363.     {
  1364.       get_spec_stats (s2, s1->length);
  1365.       if (s2->has_restricted_char_class)
  1366.     {
  1367.       error (1, 0,
  1368.          "when translating, the only character classes that may appear in\n\
  1369. \tstring2 are `upper' and `lower'");
  1370.     }
  1371.  
  1372.       if (s2->n_indefinite_repeats > 1)
  1373.     {
  1374.       error (1, 0, "only one [c*] repeat construct may appear in string2");
  1375.     }
  1376.  
  1377.       if (translating)
  1378.     {
  1379.       if (s2->has_equiv_class)
  1380.         {
  1381.           error (1, 0,
  1382.              "[=c=] expressions may not appear in string2 when translating");
  1383.         }
  1384.  
  1385.       if (s1->length > s2->length)
  1386.         {
  1387.           if (!truncate_set1)
  1388.         {
  1389.           /* string2 must be non-empty unless --truncate-set1 is
  1390.              given or string1 is empty. */
  1391.  
  1392.           if (s2->length == 0)
  1393.             error (1, 0,
  1394.              "when not truncating set1, string2 must be non-empty");
  1395.           string2_extend (s1, s2);
  1396.         }
  1397.         }
  1398.  
  1399.       if (complement && s2->has_upper_or_lower)
  1400.         error (1, 0,
  1401.            "character classes may not be used when translating and complementing");
  1402.     }
  1403.       else
  1404.     /* Not translating. */
  1405.     {
  1406.       if (s2->n_indefinite_repeats > 0)
  1407.         error (1, 0,
  1408.            "the [c*] construct may appear in string2 only when translating");
  1409.     }
  1410.     }
  1411. }
  1412.  
  1413. /* Read buffers of SIZE bytes via the function READER (if READER is
  1414.    NULL, read from stdin) until EOF.  When non-NULL, READER is either
  1415.    read_and_delete or read_and_xlate.  After each buffer is read, it is
  1416.    processed and written to stdout.  The buffers are processed so that
  1417.    multiple consecutive occurrences of the same character in the input
  1418.    stream are replaced by a single occurrence of that character if the
  1419.    character is in the squeeze set. */
  1420.  
  1421. static void
  1422. squeeze_filter (buf, size, reader)
  1423.      unsigned char *buf;
  1424.      long int size;
  1425.      PFI reader;
  1426. {
  1427.   unsigned int char_to_squeeze = NOT_A_CHAR;
  1428.   int i = 0;
  1429.   int nr = 0;
  1430.  
  1431.   for (;;)
  1432.     {
  1433.       int begin;
  1434.  
  1435.       if (i >= nr)
  1436.     {
  1437.       if (reader == NULL)
  1438.         nr = read (0, (char *) buf, size);
  1439.       else
  1440.         nr = (*reader) (buf, size, NULL);
  1441.  
  1442.       if (nr < 0)
  1443.         error (1, errno, "read error");
  1444.       if (nr == 0)
  1445.         break;
  1446.       i = 0;
  1447.     }
  1448.  
  1449.       begin = i;
  1450.  
  1451.       if (char_to_squeeze == NOT_A_CHAR)
  1452.     {
  1453.       int out_len;
  1454.       /* Here, by being a little tricky, we can get a significant
  1455.          performance increase in most cases when the input is
  1456.          reasonably large.  Since tr will modify the input only
  1457.          if two consecutive (and identical) input characters are
  1458.          in the squeeze set, we can step by two through the data
  1459.          when searching for a character in the squeeze set.  This
  1460.          means there may be a little more work in a few cases and
  1461.          perhaps twice as much work in the worst cases where most
  1462.          of the input is removed by squeezing repeats.  But most
  1463.          uses of this functionality seem to remove less than 20-30%
  1464.          of the input. */
  1465.       for (; i < nr && !in_squeeze_set[buf[i]]; i += 2)
  1466.         ;            /* empty */
  1467.  
  1468.       /* There is a special case when i == nr and we've just
  1469.          skipped a character (the last one in buf) that is in
  1470.          the squeeze set. */
  1471.       if (i == nr && in_squeeze_set[buf[i - 1]])
  1472.         --i;
  1473.  
  1474.       if (i >= nr)
  1475.         out_len = nr - begin;
  1476.       else
  1477.         {
  1478.           char_to_squeeze = buf[i];
  1479.           /* We're about to output buf[begin..i]. */
  1480.           out_len = i - begin + 1;
  1481.  
  1482.           /* But since we stepped by 2 in the loop above,
  1483.          out_len may be one too large. */
  1484.           if (i > 0 && buf[i - 1] == char_to_squeeze)
  1485.         --out_len;
  1486.  
  1487.           /* Advance i to the index of first character to be
  1488.          considered when looking for a char different from
  1489.          char_to_squeeze. */
  1490.           ++i;
  1491.         }
  1492.       if (out_len > 0
  1493.           && fwrite ((char *) &buf[begin], 1, out_len, stdout) == 0)
  1494.         error (1, errno, "write error");
  1495.     }
  1496.  
  1497.       if (char_to_squeeze != NOT_A_CHAR)
  1498.     {
  1499.       /* Advance i to index of first char != char_to_squeeze
  1500.          (or to nr if all the rest of the characters in this
  1501.          buffer are the same as char_to_squeeze). */
  1502.       for (; i < nr && buf[i] == char_to_squeeze; i++)
  1503.         ;            /* empty */
  1504.       if (i < nr)
  1505.         char_to_squeeze = NOT_A_CHAR;
  1506.       /* If (i >= nr) we've squeezed the last character in this buffer.
  1507.          So now we have to read a new buffer and continue comparing
  1508.          characters against char_to_squeeze. */
  1509.     }
  1510.     }
  1511. }
  1512.  
  1513. /* Read buffers of SIZE bytes from stdin until one is found that
  1514.    contains at least one character not in the delete set.  Store
  1515.    in the array BUF, all characters from that buffer that are not
  1516.    in the delete set, and return the number of characters saved
  1517.    or 0 upon EOF. */
  1518.  
  1519. static long
  1520. read_and_delete (buf, size, not_used)
  1521.      unsigned char *buf;
  1522.      long int size;
  1523.      PFI not_used;
  1524. {
  1525.   long n_saved;
  1526.   static int hit_eof = 0;
  1527.  
  1528.   assert (not_used == NULL);
  1529.   assert (size > 0);
  1530.  
  1531.   if (hit_eof)
  1532.     return 0;
  1533.  
  1534.   /* This enclosing do-while loop is to make sure that
  1535.      we don't return zero (indicating EOF) when we've
  1536.      just deleted all the characters in a buffer. */
  1537.   do
  1538.     {
  1539.       int i;
  1540.       int nr = read (0, (char *) buf, size);
  1541.  
  1542.       if (nr < 0)
  1543.     error (1, errno, "read error");
  1544.       if (nr == 0)
  1545.     {
  1546.       hit_eof = 1;
  1547.       return 0;
  1548.     }
  1549.  
  1550.       /* This first loop may be a waste of code, but gives much
  1551.          better performance when no characters are deleted in
  1552.          the beginning of a buffer.  It just avoids the copying
  1553.          of buf[i] into buf[n_saved] when it would be a NOP. */
  1554.  
  1555.       for (i = 0; i < nr && !in_delete_set[buf[i]]; i++)
  1556.     /* empty */ ;
  1557.       n_saved = i;
  1558.  
  1559.       for (++i; i < nr; i++)
  1560.     if (!in_delete_set[buf[i]])
  1561.       buf[n_saved++] = buf[i];
  1562.     }
  1563.   while (n_saved == 0);
  1564.  
  1565.   return n_saved;
  1566. }
  1567.  
  1568. /* Read at most SIZE bytes from stdin into the array BUF.  Then
  1569.    perform the in-place and one-to-one mapping specified by the global
  1570.    array `xlate'.  Return the number of characters read, or 0 upon EOF. */
  1571.  
  1572. static long
  1573. read_and_xlate (buf, size, not_used)
  1574.      unsigned char *buf;
  1575.      long int size;
  1576.      PFI not_used;
  1577. {
  1578.   long chars_read = 0;
  1579.   static int hit_eof = 0;
  1580.   int i;
  1581.  
  1582.   assert (not_used == NULL);
  1583.   assert (size > 0);
  1584.  
  1585.   if (hit_eof)
  1586.     return 0;
  1587.  
  1588.   chars_read = read (0, (char *) buf, size);
  1589.   if (chars_read < 0)
  1590.     error (1, errno, "read error");
  1591.   if (chars_read == 0)
  1592.     {
  1593.       hit_eof = 1;
  1594.       return 0;
  1595.     }
  1596.  
  1597.   for (i = 0; i < chars_read; i++)
  1598.     buf[i] = xlate[buf[i]];
  1599.  
  1600.   return chars_read;
  1601. }
  1602.  
  1603. /* Initialize a boolean membership set IN_SET with the character
  1604.    values obtained by traversing the linked list of constructs S
  1605.    using the function `get_next'.  If COMPLEMENT_THIS_SET is
  1606.    non-zero the resulting set is complemented. */
  1607.  
  1608. static void
  1609. set_initialize (s, complement_this_set, in_set)
  1610.      struct Spec_list *s;
  1611.      int complement_this_set;
  1612.      SET_TYPE *in_set;
  1613. {
  1614.   int c;
  1615.   int i;
  1616.  
  1617.   bzero (in_set, N_CHARS * sizeof (in_set[0]));
  1618.   s->state = BEGIN_STATE;
  1619.   while ((c = get_next (s, NULL)) != -1)
  1620.     in_set[c] = 1;
  1621.   if (complement_this_set)
  1622.     for (i = 0; i < N_CHARS; i++)
  1623.       in_set[i] = (!in_set[i]);
  1624. }
  1625.  
  1626. void
  1627. main (argc, argv)
  1628.      int argc;
  1629.      char **argv;
  1630. {
  1631.   int c;
  1632.   int non_option_args;
  1633.   struct Spec_list buf1, buf2;
  1634.   struct Spec_list *s1 = &buf1;
  1635.   struct Spec_list *s2 = &buf2;
  1636.  
  1637.   program_name = argv[0];
  1638.  
  1639.   while ((c = getopt_long (argc, argv, "cdst", long_options,
  1640.                (int *) 0)) != EOF)
  1641.     {
  1642.       switch (c)
  1643.     {
  1644.     case 0:
  1645.       break;
  1646.  
  1647.     case 'c':
  1648.       complement = 1;
  1649.       break;
  1650.  
  1651.     case 'd':
  1652.       delete = 1;
  1653.       break;
  1654.  
  1655.     case 's':
  1656.       squeeze_repeats = 1;
  1657.       break;
  1658.  
  1659.     case 't':
  1660.       truncate_set1 = 1;
  1661.       break;
  1662.  
  1663.     default:
  1664.       usage ();
  1665.       break;
  1666.     }
  1667.     }
  1668.  
  1669.   if (flag_version)
  1670.     {
  1671.       fprintf (stderr, "%s\n", version_string);
  1672.       exit (0);
  1673.     }
  1674.  
  1675.   if (flag_help)
  1676.     usage ();
  1677.  
  1678.   posix_pedantic = (getenv ("POSIXLY_CORRECT") != NULL);
  1679.  
  1680.   non_option_args = argc - optind;
  1681.   translating = (non_option_args == 2 && !delete);
  1682.  
  1683.   /* Change this test if it is legal to give tr no options and
  1684.      no args at all.  POSIX doesn't specifically say anything
  1685.      either way, but it looks like they implied it's illegal
  1686.      by omission.  If you want to make tr do a slow imitation
  1687.      of `cat' use `tr a a'. */
  1688.   if (non_option_args > 2)
  1689.     usage ();
  1690.  
  1691.   if (!delete && !squeeze_repeats && non_option_args != 2)
  1692.     error (1, 0, "two strings must be given when translating");
  1693.  
  1694.   if (delete && squeeze_repeats && non_option_args != 2)
  1695.     error (1, 0, "two strings must be given when both \
  1696. deleting and squeezing repeats");
  1697.  
  1698.   /* If --delete is given without --squeeze-repeats, then
  1699.      only one string argument may be specified.  But POSIX
  1700.      says to ignore any string2 in this case, so if POSIXLY_CORRECT
  1701.      is set, pretend we never saw string2.  But I think
  1702.      this deserves a fatal error, so that's the default. */
  1703.   if ((delete && !squeeze_repeats) && non_option_args != 1)
  1704.     {
  1705.       if (posix_pedantic && non_option_args == 2)
  1706.     --non_option_args;
  1707.       else
  1708.     error (1, 0,
  1709.            "only one string may be given when deleting without squeezing repeats");
  1710.     }
  1711.  
  1712.   spec_init (s1);
  1713.   if (parse_str ((unsigned char *) argv[optind], s1))
  1714.     exit (1);
  1715.  
  1716.   if (non_option_args == 2)
  1717.     {
  1718.       spec_init (s2);
  1719.       if (parse_str ((unsigned char *) argv[optind + 1], s2))
  1720.     exit (1);
  1721.     }
  1722.   else
  1723.     s2 = NULL;
  1724.  
  1725.   validate (s1, s2);
  1726.  
  1727.   if (squeeze_repeats && non_option_args == 1)
  1728.     {
  1729.       set_initialize (s1, complement, in_squeeze_set);
  1730.       squeeze_filter (io_buf, IO_BUF_SIZE, NULL);
  1731.     }
  1732.   else if (delete && non_option_args == 1)
  1733.     {
  1734.       int nr;
  1735.  
  1736.       set_initialize (s1, complement, in_delete_set);
  1737.       do
  1738.     {
  1739.       nr = read_and_delete (io_buf, IO_BUF_SIZE, NULL);
  1740.       if (nr > 0 && fwrite ((char *) io_buf, 1, nr, stdout) == 0)
  1741.         error (1, errno, "write error");
  1742.     }
  1743.       while (nr > 0);
  1744.     }
  1745.   else if (squeeze_repeats && delete && non_option_args == 2)
  1746.     {
  1747.       set_initialize (s1, complement, in_delete_set);
  1748.       set_initialize (s2, 0, in_squeeze_set);
  1749.       squeeze_filter (io_buf, IO_BUF_SIZE, (PFI) read_and_delete);
  1750.     }
  1751.   else if (translating)
  1752.     {
  1753.       if (complement)
  1754.     {
  1755.       int i;
  1756.       SET_TYPE *in_s1 = in_delete_set;
  1757.  
  1758.       set_initialize (s1, 0, in_s1);
  1759.       s2->state = BEGIN_STATE;
  1760.       for (i = 0; i < N_CHARS; i++)
  1761.         xlate[i] = i;
  1762.       for (i = 0; i < N_CHARS; i++)
  1763.         {
  1764.           if (!in_s1[i])
  1765.         {
  1766.           int ch = get_next (s2, NULL);
  1767.           assert (ch != -1 || truncate_set1);
  1768.           if (ch == -1)
  1769.             {
  1770.               /* This will happen when tr is invoked like e.g.
  1771.              tr -cs A-Za-z0-9 '\012'.  */
  1772.               break;
  1773.             }
  1774.           xlate[i] = ch;
  1775.         }
  1776.         }
  1777.       assert (get_next (s2, NULL) == -1 || truncate_set1);
  1778.     }
  1779.       else
  1780.     {
  1781.       int c1, c2;
  1782.       int i;
  1783.       enum Upper_Lower_class class_s1;
  1784.       enum Upper_Lower_class class_s2;
  1785.  
  1786.       for (i = 0; i < N_CHARS; i++)
  1787.         xlate[i] = i;
  1788.       s1->state = BEGIN_STATE;
  1789.       s2->state = BEGIN_STATE;
  1790.       for (;;)
  1791.         {
  1792.           c1 = get_next (s1, &class_s1);
  1793.           c2 = get_next (s2, &class_s2);
  1794.           if (!class_ok[(int) class_s1][(int) class_s2])
  1795.         error (1, 0,
  1796.              "misaligned or mismatched upper and/or lower classes");
  1797.           /* The following should have been checked by validate... */
  1798.           if (c2 == -1)
  1799.         break;
  1800.           xlate[c1] = c2;
  1801.         }
  1802.       assert (c1 == -1 || truncate_set1);
  1803.     }
  1804.       if (squeeze_repeats)
  1805.     {
  1806.       set_initialize (s2, 0, in_squeeze_set);
  1807.       squeeze_filter (io_buf, IO_BUF_SIZE, (PFI) read_and_xlate);
  1808.     }
  1809.       else
  1810.     {
  1811.       int chars_read;
  1812.  
  1813.       do
  1814.         {
  1815.           chars_read = read_and_xlate (io_buf, IO_BUF_SIZE, NULL);
  1816.           if (chars_read > 0
  1817.           && fwrite ((char *) io_buf, 1, chars_read, stdout) == 0)
  1818.         error (1, errno, "write error");
  1819.         }
  1820.       while (chars_read > 0);
  1821.     }
  1822.     }
  1823.  
  1824.   if (fclose (stdout) == EOF)
  1825.     error (2, errno, "write error");
  1826.  
  1827.   if (close (0) != 0)
  1828.     error (2, errno, "standard input");
  1829.  
  1830.   exit (0);
  1831. }
  1832.